package com.haopt.clock.service.impl;

import com.haopt.clock.dao.TUserMapper;
import com.haopt.clock.dto.ResultDTO;
import com.haopt.clock.entity.TUser;
import com.haopt.clock.service.UserService;
import com.haopt.clock.utils.BeanHelper;
import com.haopt.clock.utils.DataUtil;
import com.haopt.clock.utils.IdBuilderUtil;
import com.haopt.clock.vo.ReqApplicationVO;
import com.haopt.clock.vo.ReqUserAddVO;
import com.haopt.clock.vo.ReqUserApplicationPageVO;
import com.haopt.clock.vo.ResUserAddVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author haopt
 * @version 1.0
 * @ClassName UserServiceImpl
 * @Description 用户模块业务端
 * @date 2021/3/21 20:31
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TUserMapper userMapper;

    @Transactional
    @Override
    public ResultDTO<ResUserAddVO> add(ReqUserAddVO vo) {
        if (DataUtil.isNullOrEmpty(vo.getOpenId())) {
            System.out.println(vo);
            System.out.println("当前openid不存在");
            return ResultDTO.errorOf(4001, "网络繁忙，请从新");
        }
        //看看用户是否为第一次登录
        TUser userSearch = new TUser();
        userSearch.setOpenId(vo.getOpenId());
        int count = userMapper.selectCount(userSearch);
        TUser user = new TUser();
        if (count == 0) {
            //新增用户信息
            user = BeanHelper.copyProperties(vo, TUser.class);
            user.setId(IdBuilderUtil.getId());
            user.setRole(1);
            user.setCreateTime(System.currentTimeMillis());
            userMapper.insertSelective(user);
        } else {
            //获取存在用户信息
            TUser searchBean = new TUser();
            searchBean.setOpenId(vo.getOpenId());
            TUser user1 = userMapper.selectOne(searchBean);
            //编辑用户信息
            TUser user2 = BeanHelper.copyProperties(vo, TUser.class);
            user2.setId(user1.getId());
            userMapper.updateByPrimaryKeySelective(user2);
            //获取最新的用户信息
            user = userMapper.selectOne(userSearch);
        }
        ResUserAddVO resVo = BeanHelper.copyProperties(user, ResUserAddVO.class);
        return ResultDTO.okOf(resVo);
    }

    @Override
    public String getOpenId(String appId, String code, String secret) {
        return getopenid(appId, code, secret);
    }


    public String getopenid(String appid, String code, String secret) {
        BufferedReader in = null;
        //appid和secret是开发者分别是小程序ID和小程序密钥，开发者通过微信公众平台-》设置-》开发设置就可以直接获取，
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            URL weChatUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = weChatUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            System.out.println(sb.toString());
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
// 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public String post(String strURL) {
        BufferedReader reader = null;
        String openId = "";
        try {
            // 创建连接
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 设置接收数据的格式
            // connection.setRequestProperty("Accept", "application/json");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            // utf-8编码
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.flush();
            out.close();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder res = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            System.out.println(res);
            reader.close();
            openId = res.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return openId;
    }
}
